package org.blame.lotterysystem.dao.handle;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.symmetric.AES;
import jakarta.servlet.annotation.HandlesTypes;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.blame.lotterysystem.dao.dataObject.Encrypt;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@MappedTypes(Encrypt.class) //被处理的类型
@MappedJdbcTypes(JdbcType.VARCHAR)//转换后JDBC的类型
public class EncryptTypeHandle extends BaseTypeHandler<Encrypt> {
    private final byte[] KEYS= "123456789abcdefg".getBytes(StandardCharsets.UTF_8);

    /**设置参数
     *
     * @param ps   SQL的预设对象
     * @param i    需要赋值的索引位置
     * @param parameter 原本位置i需要赋的值
     * @param jdbcType  jdbc 类型
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Encrypt parameter, JdbcType jdbcType) throws SQLException {
        if(parameter==null || parameter.getValue()==null){
            ps.setString(i,null);
            return;
        }
        System.out.println("加密的内容"+parameter.getValue());

        AES aes= SecureUtil.aes(KEYS);
        String resultEncrypt=aes.encryptHex(parameter.getValue());
        ps.setString(i,resultEncrypt);
    }

    /**获得值
     *
     * @param rs    结果集
     * @param columnName    索引名
     * @return
     * @throws SQLException
     */
    @Override
    public Encrypt getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return decrypt(rs.getString(columnName));
    }


    /**获得值
     *
     * @param rs    结果集合
     * @param columnIndex   索引
     * @return
     * @throws SQLException
     */
    @Override
    public Encrypt getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return decrypt(rs.getString(columnIndex));
    }

    /**获得值
     *
     * @param cs    结果集合
     * @param columnIndex   索引
     * @return
     * @throws SQLException
     */
    @Override
    public Encrypt getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return decrypt(cs.getString(columnIndex));    }


    /**
     * 解密
     */

    public Encrypt decrypt(String s){
        if(!StringUtils.hasText(s)){
            return null;
        }
        return new Encrypt(SecureUtil.aes(KEYS).decryptStr(s));
    }
}


